﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using SubSonic.Sugar;
using System.Security;
using MediaMonitor.Common;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Net;
using System.Configuration;
using Telerik.Web.UI;

namespace MediaMonitor.Admin
{
    public partial class User_Mgmt_PdfNews : Adex.BasePage
    {
        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        int cid = 0;
        private static string AppName = ConfigurationManager.AppSettings["AppName"].ToString();
        private static string AdminEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString();


        private iTextSharp.text.Font PDF_FONT_DEFAULT;
        private iTextSharp.text.Font PDF_FONT_TH;
        private iTextSharp.text.Font PDF_FONT_BOLD;
        private iTextSharp.text.Font PDF_FONT_GRAY;
        private iTextSharp.text.Font PDF_FONT_LIGHTGRAY;
        private iTextSharp.text.Font PDF_FONT_TITLE;
        private iTextSharp.text.Font PDF_FONT_HEADING;
        private iTextSharp.text.Font PDF_FONT_HEADING_GRAY;
        private iTextSharp.text.Font PDF_FONT_BIG;
        private iTextSharp.text.Font PDF_FONT_BIG_BOLD;
        private iTextSharp.text.Font PDF_FONT_NAV;
        private iTextSharp.text.Font PDF_FONT_GridElements;

        protected void Page_Init(object sender, EventArgs e)
        {
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            string fontpath = Server.MapPath("../");
            BaseFont customfont = BaseFont.CreateFont(fontpath + "Fonts/KOKILA.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font Kokila = new Font(customfont, 44, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_TITLE = Kokila;
            BaseFont customfontarial = BaseFont.CreateFont(fontpath + "Fonts/ARIAL.TTF", BaseFont.CP1252, BaseFont.EMBEDDED);
            Font ARIAL = new Font(customfontarial, 11, Font.BOLD, BaseColor.BLACK);
            Font ARIAL11 = new Font(customfontarial, 11, Font.BOLD, BaseColor.BLACK);
            Font ARIALNORMAL11 = new Font(customfontarial, 11, Font.NORMAL, BaseColor.BLACK);
            Font ARIALNORMAL7 = new Font(customfontarial, 7, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_DEFAULT = ARIALNORMAL11;
            PDF_FONT_TH = ARIAL;
            PDF_FONT_BOLD = ARIAL11;
            PDF_FONT_GRAY = new Font(bf, 14, Font.NORMAL, BaseColor.DARK_GRAY);
            PDF_FONT_LIGHTGRAY = new Font(bf, 15, Font.NORMAL, new BaseColor(System.Drawing.Color.FromArgb(141, 141, 141)));
            PDF_FONT_HEADING = new Font(bf, 16, Font.BOLD, BaseColor.WHITE);
            PDF_FONT_HEADING_GRAY = new Font(bf, 18, Font.BOLD, BaseColor.GRAY);
            PDF_FONT_BIG = new Font(bf, 14, Font.NORMAL, BaseColor.BLACK);
            PDF_FONT_BIG_BOLD = new Font(bf, 14, Font.BOLD, BaseColor.BLACK);
            PDF_FONT_NAV = new Font(bf, 14, Font.BOLD, BaseColor.RED);
            PDF_FONT_GridElements = ARIALNORMAL7;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);
                SetCalendarDates();
                hdnCompanyID.Value = Utility.GetRequestedVal("cid", "0");
               cid= Convert.ToInt32(Utility.GetRequestedVal("cid", "0"));
              
            }
        }

        private void SetCalendarDates()
        {


            DataTable dt = NewsLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];


            foreach (DataRow dr in dt.Rows)
            {

                RadCalendarDay d1 = new RadCalendarDay(calS);
                d1.Date = Utility.ToDateTime(dr["RFDate"]);
                d1.IsDisabled = false;
                d1.IsSelectable = true;

                d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d1.ItemStyle.ForeColor = System.Drawing.Color.White;

                calS.SpecialDays.Add(d1);

                RadCalendarDay d2 = new RadCalendarDay(calE);
                d2.Date = Utility.ToDateTime(dr["RFDate"]);
                d2.IsDisabled = false;
                d2.IsSelectable = true;

                d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d2.ItemStyle.ForeColor = System.Drawing.Color.White;


                calE.SpecialDays.Add(d2);
            }



        }

        protected void radGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {

            DataTable dt;

            if (hdnCompanyID.Value == "0")

                dt = VSiteUser.Query().SetSelectList("*").WHERE("RoleName", "user").ORDER_BY("UserName").ExecuteDataSet().Tables[0];

            else
                dt = VSiteUser.Query().SetSelectList("*").WHERE("CompanyCode", hdnCompanyID.Value).ORDER_BY("UserName").ExecuteDataSet().Tables[0];

            radGrid.DataSource = dt;

        }

        //protected void btnSend_Clicked(object sender, EventArgs e)
        //{

        //    bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
        //    bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);

        //    if (sDate < Utility.ToDateTime("01/01/2000"))
        //        sDate = Utility.ToDateTime("01/01/2000");

        //    if (eDate < Utility.ToDateTime("01/01/2000"))
        //        eDate = Utility.ToDateTime("01/01/2000");

        //    if ((sDate.ToString() != "") && (eDate.ToString() != ""))
        //    {
        //        GetPDF();

        //    }
        //    else
        //    {
        //        string script = "alert(\"Select date first!\");";
        //        ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

        //    }

        //}
        //private void GetPDF()
        //{

        //    DataSet dsCommercialPDF = new Common.ReportFuncs().GetReportCommercialPdf(Convert.ToInt32(Utility.GetRequestedVal("cid", "0")), Utility.ToDateTime(sDate as object), Utility.ToDateTime(eDate as object));
        //    if ((dsCommercialPDF.Tables[0].Rows.Count > 0) || (dsCommercialPDF.Tables[1].Rows.Count > 0) || (dsCommercialPDF.Tables[2].Rows.Count > 0))
        //    {
        //        DataTable dtTV = dsCommercialPDF.Tables[0];
        //        DataTable dtRadio = dsCommercialPDF.Tables[1];
        //        DataTable dtPress = dsCommercialPDF.Tables[2];

        //        Company company = new Company(hdnCompanyID.Value);
        //        string pdfImg1 = "_DEFAULT_1.JPG";
        //        string pdfImg2 = "_DEFAULT_2.JPG";

        //        string TemplateName = " Default";
        //        if (company.NewsTemplate != null)
        //            TemplateName = " " + company.NewsTemplate.TemplateName;
        //        string fileName = "Flash Informativo" + TemplateName + " " + DateTime.Now.ToString("dd - MM - yy");

        //        if (company.NewsTemplateID > 0)
        //        {
        //            pdfImg1 = company.NewsTemplate.Picture1;
        //            pdfImg2 = company.NewsTemplate.Picture2;
        //        }

        //        string homeImageFilePath = Server.MapPath("~") + "\\images\\templates\\" + pdfImg1;
        //        string subImageFilePath = Server.MapPath("~") + "\\images\\templates\\" + pdfImg2;
        //        // PDF GENERATEION - start

        //        iTextSharp.text.Image bgHomePage = iTextSharp.text.Image.GetInstance(homeImageFilePath);
        //        iTextSharp.text.Image bgSubPage = iTextSharp.text.Image.GetInstance(subImageFilePath);
        //        iTextSharp.text.Rectangle PdfPageSize = new iTextSharp.text.Rectangle(bgHomePage.Width, bgHomePage.Height);
        //        iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PdfPageSize);

        //        bgHomePage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;
        //        bgSubPage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;

        //        bgHomePage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);
        //        bgSubPage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);

        //        bgHomePage.SetAbsolutePosition(0, 0);
        //        bgSubPage.SetAbsolutePosition(0, 0);

        //        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

        //        // Our custom Header and Footer is done using Event Handler
        //        TwoColumnHeaderFooter PageEventHandler = new TwoColumnHeaderFooter();
        //        writer.PageEvent = PageEventHandler;

        //        // Define the page header
        //        pdfDoc.Open();
        //        CreatePDFPage_Home(pdfDoc, writer, bgHomePage, "NEW COMMERCIALS");
        //        CreatePDFPage_Criteria(pdfDoc, writer, bgSubPage, Utility.ToDateTime(sDate), Utility.ToDateTime(eDate));
        //        CreatePDFPage_TVList(pdfDoc, writer, bgSubPage, dtTV);
        //        CreatePDFPage_RADIOList(pdfDoc, writer, bgSubPage, dtRadio);
        //        CreatePDFPage_PRESSList(pdfDoc, writer, bgSubPage, dtPress);

        //        pdfDoc.Close();
        //        Response.ContentType = "application/pdf";
        //        Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
        //        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //        Response.Write(pdfDoc);
        //        Response.End();
        //        // PDF GENERATION - end
        //    }
        //    else
        //    {
        //        string script = "alert(\"No Record Exists!\");";
        //        ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

        //    }
        //}

        protected void btnSend_Clicked(object sender, EventArgs e)
        {
            ReportFuncs rep = new ReportFuncs();
            DataTable dt = rep.GetUserIDAndRolle(Session["UserID"].ToString());

            string Role = dt.Rows[0][2].ToString();
            bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
            bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);
            String selEmail = String.Empty;


            if (sDate < Utility.ToDateTime("01/01/2000"))
                sDate = Utility.ToDateTime("01/01/2000");

            if (eDate < Utility.ToDateTime("01/01/2000"))
                eDate = Utility.ToDateTime("01/01/2000");


            foreach (Telerik.Web.UI.GridItem itm in radGrid.SelectedItems)
            {
                selEmail += radGrid.MasterTableView.DataKeyValues[itm.ItemIndex]["Email"].ToString() + ",";

            }//end loop


            if ((sDate.ToString() != "01/01/2000 12:00:00 AM") && (eDate.ToString() != "01/01/2000 12:00:00 AM"))
            {
                if (selEmail == String.Empty)
                {
                    string script = "alert(\"Please select atleast one user!\");";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
                }
                else
                {
                    if (Role == "advanced user" || Role == "admin")
                        SendMail(selEmail, sDate.ToString().Replace('/', '_'), eDate.ToString().Replace('/', '_'));
                    else
                    {
                        string script = "alert(\"You have no authority to send mail!\");";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
                    }
                }

            }
            else
            {

                string script = "alert(\"Please select date first!\");";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);

            }

        }
      

        private void SendMail(String Users,string sdate,string edate)
        {

            String msg = "Estimados clientes,<br/><br/>Adjunto le anexamos el Link para la descarga del Flash informativo correspondiente al día de hoy " + DateTime.Now.ToShortDateString() + "<br/><br/>Esperamos que esta información sea de utilidad<br/><br/>Ruego nos contacten por este medio si necesitan alguna aclaratoria o ayuda adicional.<br/><br/><br/><a href='http://mediamonitor.do/pdfNews.aspx?cid=" + hdnCompanyID.Value + "&sd=" + sdate + "&ed=" + edate + "' target='_blank'>Click para descargar el PDF</a>";
            String title = "Flash Informativo AGB";
            String toAccount = Users;
            //  String toAccount = "niteshguleria@nascenture.com";
            String MyHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
            String MySMTPPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
            String MySMTPSSL = ConfigurationManager.AppSettings["SMTPSSL"].ToString();

            String fromAddr = AdminEmail;   //Email Address of Sender
            
            MailMessage smtpMssg = new MailMessage();
            smtpMssg.From = new MailAddress(fromAddr);

            if (toAccount.Contains(","))
            {
                string[] tos = toAccount.Split(',');
                for (int i = 0; i < tos.Length; i++)
                {
                    if (tos[i] == "," || tos[i] == "")
                    {
                    }
                    else
                    {
                        smtpMssg.To.Add(new MailAddress(tos[i].Replace(",", "")));
                    }
                }
            }
            else
            {
                smtpMssg.To.Add(new MailAddress(toAccount));
            }

            smtpMssg.Subject = title;
            smtpMssg.Body = msg;
            smtpMssg.IsBodyHtml = true;
            
            //smtpMssg.Attachments.Add(new Attachment(memoryStream, "News.pdf"));

            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(MyHost, Convert.ToInt32(MySMTPPort));
            //smtpClient.Timeout = 2147483647;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (MySMTPSSL == "true")
            {
                smtpClient.EnableSsl = true;
            }

            try
            {
                smtpClient.Send(smtpMssg);

            }
            catch (Exception ex)
            {

                throw new Exception("Email not sent | Reason: [" + ex.Message + "]");

            }
        }
     


    
    }
}